package com.LLL.customer.dao;

import com.LLL.DBUtill;
import com.LLL.customer.model.Customer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class CustomerDao {
    public Customer getCustomerByName(String username) {
        Connection conn = DBUtill.getConnection();
        String sql = "select * from tb_customer where user_name=?";
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            rs = ps.executeQuery();
            if (rs.next()) {
                Customer customer = new Customer();
                customer.setId(rs.getInt("id"));
                customer.setUser_name(rs.getString("user_name"));
                customer.setPassword(rs.getString("password"));
                customer.setReal_name(rs.getString("real_name"));
                customer.setMobile(rs.getString("mobile"));
                customer.setEmail(rs.getString("email"));
                customer.setPassword_question(rs.getString("password_question"));
                customer.setPassword_hint_answer(rs.getString("password_hint_answer"));
                return customer;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtill.clossResource(conn, ps, rs);
        }
        return null;
    }
    /** 根据用户名及密码添加会员信息*/
    public int addCustomer(String username, String password) {
        Customer customer = getCustomerByName(username);
        if (customer == null) {
            Connection conn = DBUtill.getConnection();
            String sql = "INSERT INTO tb_customer(`user_name`,`password`) VALUES (?,?)";
            PreparedStatement ps = null;
            try{
                ps = conn.prepareStatement(sql);
                ps.setString(1,username);
                ps.setString(2,password);
                //执行并更新数据库，返回数据库中受影响的行数
                int num = ps.executeUpdate();
                return num;
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally {
                DBUtill.clossResource(conn, ps, null);
            }
        }else{
            return 0;
        }
    }
}
